﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Entities;
using System.Data.Objects.DataClasses;
using System.Data;
using System.Linq.Expressions;

/// <summary>
/// Summary description for DALHelper
/// </summary>
namespace Libraries
{
    public class DataHelper<T> where T : EntityBase
    {
        DataContextFramework _DataContext;
        public DataHelper()
        {
            _DataContext = new DataContextFramework();
        }

        public List<T> FindAll()
        {
            return _DataContext.CreateQuery<T>(string.Concat(typeof(T).Name, "Set")).ToList();   
        }

        public T GetObjectByID(int entityId)
        {
            return _DataContext.CreateQuery<T>(string.Concat(typeof(T).Name, "Set")).Where(r => r.ID == entityId).FirstOrDefault();
        }

        public void AddObject(T entity)
        {
            _DataContext.AddObject(entity.GetType().Name + "Set", entity);            
        }
        public void DeleteObject(int entityId)
        {
            var objDelete = _DataContext.CreateQuery<T>(string.Concat(typeof(T).Name, "Set")).Where(r => r.ID == entityId).FirstOrDefault();
            _DataContext.DeleteObject(objDelete);            
        }
        public void DeleteObject(List<int> entityId)
        {
            foreach (var itemId in entityId)
            {
                DeleteObject(itemId);
            }            
        }
        public void UpdateObject(T entity)
        {
            var objUpdate = _DataContext.CreateQuery<T>(string.Concat(typeof(T).Name, "Set")).Where(r => r.ID == entity.ID).FirstOrDefault();
            objUpdate = entity;                     
        }

        public void UpdateObject(List<T> listEntity)
        {
            foreach (var entityItem in listEntity)
            {
                UpdateObject(entityItem);   
            }            
        }
       
        public List<T> Find(Expression<Func<T, bool>> condition)
        {
            return _DataContext.CreateQuery<T>(string.Concat(typeof(T).Name, "Set")).Where(condition).ToList();
        }

        public void Commit()
        {
            _DataContext.SaveChanges();
        }
       

    }
    
}